#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         Option.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  A Option is a primitive Component
#               to represent simple true/false value in a Selection
#               with in an assessment.
#
#               Originally this component was based on the 
#               BooleanComponent in pre 1.0 versions of the 
#               KnowledgeEngine. BooleanComponent was an abstract
#               class that supported both the CheckBox component
#               and this component.  In this edition, it is a component
#               in it's own right, supporting ONLY true/false values
#               where as the CheckBox component is now Tristate.
#
# See Also:     Component, Model, Section
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Components.Selection.Selection import Selection
from Products.KnowledgeEngine.Component import Component, ComponentInfo
from Products.KnowledgeEngine.Assessible import Assessible
from Products.KnowledgeEngine.AssessmentFilter import AssessmentFilter
from Products.KnowledgeEngine.AssessmentComponentState import AssessmentComponentState
from Products.KnowledgeEngine.AssessmentComponentValueTypes import *
from Products.KnowledgeEngine.KERLExtensions import KERLExtensions
from Products.KnowledgeEngine.KERLProcessor import *
from Products.KnowledgeEngine.Scorable import *
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *
from Products.KnowledgeEngine.KERFProcessor import *
from Products.KnowledgeEngine.Graphing.Graphable import *
from Products.KnowledgeEngine.Graphing.Datum import *
from Products.KnowledgeEngine.User import User
from Products.KnowledgeEngine.Caching import RequestCache 

#####################################################################
## Zope CMF Library Imports
from Products.CMFCore.PortalContent import PortalContent
from Products.CMFCore.ActionInformation import ActionInformation
from Products.CMFCore import CMFCorePermissions
from Products.CMFCore.CMFCorePermissions import ModifyPortalContent

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from ImageFile import ImageFile

#####################################################################
## Python Library Imports
import types

#####################################################################
## OptionInfo Class Definition
class OptionInfo(ComponentInfo, ScorableInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """

    #---------------------------------------------------------------#
    
    def getClassName(self):
        return 'Option'

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Option"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "opt"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/Option_icon.gif', globals())
        
    #---------------------------------------------------------------#

    def isPermittedInContainer(self, containerClassInfo, containerInstance = None, instance=None):
        """
            ABSTRACT: Returns if class instances (instance) is permitted in 
            the specified container (containerInstance)
            
            NOTE: This is from this class' instance perspective.
        """
        
        #DEFAULT RULE: Options are only permitted in Selections
        return containerClassInfo.isInstanceOf('Selection')

    #---------------------------------------------------------------#

    def isInstanceOf(self, className):
        """
            Returns if the class is an instance of the specified
            className, or implements the interface specified 
            by the className
        """

        return className == 'Assessible' or ScorableInfo.isInstanceOf(self,className) or ComponentInfo.isInstanceOf(self, className)
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ComponentInfo.onConfigureProperties(self)
        ScorableInfo.onConfigureProperties(self)
  
        #add the 'reportContentWhenSelected' property        
        self.addPropertyDefinition(PropertyDefinition(identity="reportContentWhenSelected", displayName="Report Content (when Yes is selected)", description="Text to be displayed in a report for this component when it is true/on/yes.", defaultValue="", propertyType=pt_STRING, propertyFormat=pf_HTML, propertyStructure=ps_ATOMIC))        

        #add the 'reportContentWhenUnselected' property        
        self.addPropertyDefinition(PropertyDefinition(identity="reportContentWhenUnselected", displayName="Report Content (when No is selected)", description="Text to be displayed in a report for this component when it is false/off/no.", defaultValue="", propertyType=pt_STRING, propertyFormat=pf_HTML, propertyStructure=ps_ATOMIC))        

        #add the 'defaultValue' property        
        self.addPropertyDefinition(PropertyDefinition(identity="defaultValue", displayName="Default Value", description="The value used for this component i). in newly created assessments, ii). when added to a model and assessments already exist in that model, or iii). when not changed by a user in an assessment", defaultValue=false, propertyType=pt_BOOLEAN, propertyFormat=pf_SELECTION + pf_YES_NO, propertyStructure=ps_ATOMIC))        

        #add the 'scoreTrue' property        
        self.addPropertyDefinition(PropertyDefinition(identity="scoreTrue", displayName="Score (when Yes is selected)", description="The score for the component when Selected/On/Yes/Checked in an assessment", defaultValue=1.0, propertyType=pt_FLOAT, propertyFormat=pf_NATIVE, propertyStructure=ps_ATOMIC))        

        #add the 'scoreFalse' property        
        self.addPropertyDefinition(PropertyDefinition(identity="scoreFalse", displayName="Score (when No is selected)", description="The score for the component when Unelected/Off/No/Unchecked in an assessment", defaultValue=0.0, propertyType=pt_FLOAT, propertyFormat=pf_NATIVE, propertyStructure=ps_ATOMIC))        

    #---------------------------------------------------------------#

#####################################################################
## Option Class Definition
class Option(Component, Assessible, KERLExtensions, Scorable):
    """
        Defines a a simple component to represent a boolean selection 
        (often exclusive within a Selection component) in an assessment
    """

    #---------------------------------------------------------------#

    #TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = OptionInfo()

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the Option"        

        Component.__init__(self, id, identity)

    #---------------------------------------------------------------#

    def isPreviewPermitted(self):
        """
            Return if the component is allowed to be previewed.
            
            By default all components can be previewed, some however
            should not be previewed. eg: Options whose display is 
            dependant on their parents.
        """
        
        #options can't be previewed directly... only their parents can
        return false
        
    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """
        
        #perform Component.onAfterInstanciation processing
        Component.onAfterInstanciation(self)
        
        ###print "DEBUG: CheckBox.onAfterInstanciation: Completed"

    #---------------------------------------------------------------#

    def onAfterIdentityChange(self, identityMappings):
        """
            Handle Knowledge Engine specific actions after the 
            identity of this object has changed.
            
            The identityMappings dictionary holds 
            mappings from oldIdentities -> newIdentities
            (including this object)                        
        """

        #perform default identity changes
        Component.onAfterIdentityChange(self, identityMappings)
        
        #resolve report KERFs
        self.setReportContentWhenSelected(updateKERF(self.getReportContentWhenSelected(), identityMappings))
        self.setReportContentWhenUnselected(updateKERF(self.getReportContentWhenUnselected(), identityMappings))        
        
    #---------------------------------------------------------------#
        
    def getReportContentWhenSelected(self):
        """
            Returns the Report Content for this component
            when Yes is selected in an assessment
        """
        
        return self.reportContentWhenSelected

    #---------------------------------------------------------------#

    def setReportContentWhenSelected(self, reportContentWhenSelected):
        """
            Sets the Report Content for this component
            when Yes is selected in an assessment
        """
        
        self.reportContentWhenSelected = reportContentWhenSelected
                
    #---------------------------------------------------------------#
        
    def getReportContentWhenUnselected(self):
        """
            Returns the Report Content for this component
            when No is selected in an assessment
        """
        
        return self.reportContentWhenUnselected

    #---------------------------------------------------------------#

    def setReportContentWhenUnselected(self, reportContentWhenUnselected):
        """
            Sets the Report Content for this component
            when No is selected in an assessment
        """

        self.reportContentWhenUnselected = reportContentWhenUnselected
                
    #---------------------------------------------------------------#
        
    def getDefaultValue(self):
        """
            Returns the default value of the component 
            for new assessments; true = 1, false = 0
        """
        
        return self.defaultValue

    #---------------------------------------------------------------#

    def setDefaultValue(self, defaultValue):
        """
            Sets the default value of the component 
            for new assessments; true = 1, false = 0
        """
        
        self.defaultValue = defaultValue
        
    #---------------------------------------------------------------#

    def getComponentProperty(self, identity, propertyName, assessment = None):
        """
            Returns the value of the specified property, given the
            identity of the component (which may be used to lookup states) and
            an assessment.

            RETURNS: None if the property doesn't exist
        """

        if propertyName == "value":
            if assessment.getComponentState(identity).getValue() == true:
                return "Yes"
            else:
                return "No"
        else:
            return Component.getComponentProperty(self, identity, propertyName, assessment)

    #---------------------------------------------------------------#
        
    def getScore(self, assessment):
        """
            Evaluates the unweighted score of the component..

            Typically called by Scorable.getScore() to retrieve
            score. Or Scorable.getScore()*Scorable.getWeighting()

            NOTE: Must return a real number
        """

        #get the identity
        identity = self.getIdentity()

        #get the stored state
        state = assessment.getComponentState(identity).getValue()

        #evaluate and return the score
        if state == true:
            return self.scoreTrue           
        else:
            return self.scoreFalse  
        
    #---------------------------------------------------------------#
        
    def getMaxScore(self):
        """
            Evaluates the maximum potential score
        """

        #evaluate and return the score
        return max([self.scoreTrue, self.scoreFalse])
        
        
    #---------------------------------------------------------------#
    # BEGIN: Assessible Implementation                              #
    #---------------------------------------------------------------#
        
    def getAssessmentValueType(self):
        """
            ABSTRACT: Returns the type of the value that is to be stored
            for this component when it's assessment state is persisted.
            
            NOTE 1: See AssessmentComponentValueTypes for a list of defined contants       
            NOTE 2: This method MUST be overriden in the implementing
            class to specify the correct type for value persistence
            
            RETURN TYPE: String
        """
        
        #option assessment values are booleans
        return st_BOOLEAN
        
    #---------------------------------------------------------------#
        
    def getDefaultAssessmentState(self, assessment):
        """
            ABSTRACT: Constructs and returns a suitable 'default' 
            AssessmentComponentState for the provided Assessment
            instance.

            NOTE: This method MUST be overriden in the implementing
            class to provide a suitable default value for the component
            
            RETURN TYPE: AssessmentComponentState
        """
        
        return AssessmentComponentState(assessment.getIdentity(), assessment.getModelIdentity(), self.getIdentity(), self.getAssessmentValueType(), self.getDefaultValue())
            
    #---------------------------------------------------------------#

    def updateAssessmentState(self, assessment, formValue):
        """
            ABSTRACT: Updates the specified assessment using
            the provided HTTP REQUEST formValue.
            
            NOTE: This method MUST be overriden in the implementing
            class to suitably update the component state
        """
        
        #ensure the assessment value is a tristate
        if type(formValue) is types.StringType:
            if formValue == 'on' or formValue == 'checked' or formValue == 'selected' or formValue == 'true':
                value = true
            else:
                value = false
            
        else:
            value = formValue
            
        #get the current assessment state for the component from the assessment
        state = assessment.getComponentState(self.getIdentity())
        
        #update the current state
        state.setValue(value)
        
        #update the assessment
        assessment.setIsModified(true)
            
    #---------------------------------------------------------------#
    # END: Assessible Implementation                                #
    #---------------------------------------------------------------#
    
    #---------------------------------------------------------------#
    # BEGIN: KERLExtensions Implementation                          #
    #---------------------------------------------------------------#

    def compileKERLtoJavaScript(self, expression):
        """
            Returns a Python string that represents a JavaScript
            expression, which may be used to evaluate the status
            of the component class specific KERL expression.

            NOTE: this method is primarily used to produce
            JavaScript expressions that form the basis of the
            client-side showif technology.
            
            RETURN TYPE: String         
        """

        #example: cond="['bool1','selected']" returns 'document.getElementById("bool1").value=="true"'
        #example: cond="['bool1','unselected']" returns 'document.getElementById("bool1").value=="false"'
        #example: cond="['bool1','undefined']" returns 'document.getElementById("bool1").value!="true" && document.getElementById("bool1").value!="false"'

        #get the identity
        identity = self.getIdentity()

        #get the value
        value = expression[1]

        if value == "selected":
            return "document.getElementById(\"" + identity + "\").value==\"true\""
        elif value == "unselected":
            return "document.getElementById(\"" + identity + "\").value==\"false\""
        else:
            return "(document.getElementById(\"" + identity + "\").value!=\"true\" && document.getElementById(\"" + identity + "\").value!=\"false\")"

    #---------------------------------------------------------------#

    def compileKERLtoEnglish(self, expression):
        """
            Returns a string representing an 'English' version
            of the component class specific KERL expression.

            NOTE: this method is primarily used to produce
            English descriptions of KERL expressions that may be 
            used to describe things like AssessmentFilters
            
            RETURN TYPE: String         
        """

        #example: cond="['bool1','selected']" returns '<title> is selected'
        #example: cond="['bool1','unselected']" returns '<title> is unselected'
        #example: cond="['bool1','undefined']" returns '<title> is undefined'

        #get the identity
        identity = self.getIdentity()

        #get the value
        value = expression[1]

        if value == "selected":
            return "%s '%s' is selected" % (self.getClassInfo().getDisplayName(), self.getTitleOrId(), )
        elif value == "unselected":
            return "%s '%s' is unselected" % (self.getClassInfo().getDisplayName(), self.getTitleOrId(), )
        else:
            return "%s '%s' is undefined" % (self.getClassInfo().getDisplayName(), self.getTitleOrId(), )

    #---------------------------------------------------------------#

    def evaluate(self, expression, assessment):
        """
            Evalutes the component class specific KERL expression
            using the provided assessment.

            NOTE: this method is primarily used to produce
            JavaScript expressions that form the basis of the
            client-side showif technology.

            RETURN TYPE: Boolean         
        """
        
        #get the identity
        identity = self.getIdentity()

        #get the value
        value = expression[1]

        #get the stored state (and ensure it is a boolean)
        state = assessment.getComponentState(identity)

        #evaluate the expression
        if value == "selected":            
            return state.getValue() == true           
        else:
            return state.getValue() == false
    
    #---------------------------------------------------------------#

    def getDependencies(self, expression):
        """
            Returns a list of components that are required to
            evaluate the component class specific KERL expression.

            NOTE: Includes the specific component itself.

            RETURN TYPE: {Component} indexed by Component.getIdentity()
       """

        return {self.getIdentity():self}
    
    #---------------------------------------------------------------#

    def updateKERLIdentities(self, expression, identityMappings):
        """
            Returns the expression with the appropriate old identities
            (as identified by the identityMappings) replaced with 
            new identities.
        """
        
        #get the component identity from the expression (first element)
        identity = expression[0]
        
        #is the component in the identityMappings?
        if identityMappings.has_key(identity):
            expression[0] = identityMappings[identity]
        
        return expression

    #---------------------------------------------------------------#
    # END: KERLExtensions Implementation                            #
    #---------------------------------------------------------------#

    def generateGraphableStatistics(self, baseAssessmentFilter = None, user = None, nrAssessments = None):
        """
            Generates a Graphable instance containing statistic
            information for this component - that may be graphed.
            
            The provided assessmentFilter is used as a basis for
            generating statistics information.  Setting this to
            None (the default) means all assessments are used.
            
            RETURN TYPE: Graphable
        """
        cache = RequestCache('Option.generateGrapableStatistics', self.REQUEST)

        # Build a uniqe cache id
        modelIdentity = baseAssessmentFilter.getModelIdentity()
        for singleScope in baseAssessmentFilter.getAssessmentScope():
            singleScope += singleScope

        if type(user) == User:
            authenticatedUserIdentity = user.getIdentity()
        else:
            authenticatedUserIdentity = user

        expression = baseAssessmentFilter.expression

        c_hash = self.getIdentity() + `modelIdentity` + `expression` + `singleScope` + `authenticatedUserIdentity`

        if c_hash in cache:
            return cache[c_hash]
        
        #ensure the baseAssessmentFilter is valid (not None)
        if baseAssessmentFilter is None:
            baseAssessmentFilter = self.getModel().getAllAssessmentsFilter()
        
        #we need to use the assessment storage service to get the statistics
        assessmentStorageService = self.getModel().getAssessmentStorageService()

        #determine the number of assessments (if necessary)
        if nrAssessments is None:
            nrAssessments = assessmentStorageService.getNrAssessmentsSatisfyingFilter(baseAssessmentFilter, user)   
        
        #we need a Graphable for the results
        graphable = Graphable(self.getTitleOrId(), "The following chart outlines the selection statistics for the '%s' component in the %d current assessments." % (self.getTitleOrId(), nrAssessments), 0, nrAssessments)
        
        #create a datum for the number of times the component has been selected in the assessments
        filterTitle = "# Selected"
        filterExpression = parseKERL("['%s', 'selected']" % self.getIdentity())
        assessmentFilter = AssessmentFilter(title=filterTitle, expression=simplifyKERL(['all', baseAssessmentFilter.getExpression(), filterExpression]), model=self.getModel(), assessmentScope=baseAssessmentFilter.getAssessmentScope())

        nrSelectedAssessments = assessmentStorageService.getNrAssessmentsSatisfyingFilter(assessmentFilter, user)
        datum = Datum(identity="selected", title="# Selected.", value=nrSelectedAssessments, color="green", context={"ASSESSMENT_FILTER":assessmentFilter})
        graphable.addDatum(datum)

        #create a datum for the number of times the component has been unselected in the assessments
        filterTitle = "# Unselected"
        filterExpression = parseKERL("['%s', 'unselected']" % self.getIdentity())
        assessmentFilter = AssessmentFilter(title=filterTitle, expression=simplifyKERL(['all', baseAssessmentFilter.getExpression(), filterExpression]), model=self.getModel(), assessmentScope=baseAssessmentFilter.getAssessmentScope())

        nrUnselectedAssessments = assessmentStorageService.getNrAssessmentsSatisfyingFilter(assessmentFilter, user)
        datum = Datum(identity="unselected", title="# Unselected.", value=nrUnselectedAssessments, color="red", context={"ASSESSMENT_FILTER":assessmentFilter})
        graphable.addDatum(datum)

        #create a datum for the number of times the component has been unselected in the assessments
        datum = Datum(identity="undefined", title="# Undefined.", value=nrAssessments - nrSelectedAssessments - nrUnselectedAssessments, color="orange", footnote="As it is possible for an end-user to avoid selecting either 'yes' or 'no' for some options, some assessments may have 'undefined' values.")        
        graphable.addDatum(datum)

        cache[c_hash] = graphable        
        return graphable

    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Component Information with the Knowledge Engine
registerGenericObjectClass(Option)

#####################################################################
